package com.lysh.http.utils;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author liyishan
 * @date 2023/4/19 12:29
 */

public class SignUtils {
    private static final Logger log = LoggerFactory.getLogger(SignUtils.class);

    public SignUtils() {
    }

    public static String signature(Map<String, Object> params, String path, String secret) {
        List<String> list = new ArrayList();
        Iterator<Map.Entry<String, Object>> iter = params.entrySet().iterator();

        String md5;
        String waitSign;
        while (iter.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry) iter.next();
            md5 = (String) entry.getKey();
            if (entry.getValue() != null && !StringUtils.isBlank(entry.getValue().toString()) && !((String) entry.getKey()).equals("token")) {
                waitSign = entry.getValue().toString();
                list.add(md5 + "=" + waitSign);
            }
        }

        Collections.sort(list);
        StringBuilder buf = new StringBuilder();
        Iterator var10 = list.iterator();

        while (var10.hasNext()) {
            waitSign = (String) var10.next();
            buf.append(waitSign);
        }

        buf.append(path);
        md5 = DigestUtils.md5Hex(buf.toString());
        waitSign = md5 + secret;
        String sign = DigestUtils.sha1Hex(waitSign);
        return sign;
    }
}
